<template>
  <div class="border white_bg">
    <div class="table_content">
      <div v-if="hasHeaderOperateBar" class="header_operate_bar flex">
        <div
          v-if="hasAddButton"
          class="header_action_option"
          @click="openDia()"
        >
          <a-icon type="audit" class="r_margin2" />
          <span>新增</span>
        </div>
        <div
          v-if="hasDeleteButton"
          class="header_action_option"
          @click="multiDel()"
        >
          <a-icon type="delete" class="r_margin2" />
          <span>删除</span>
        </div>
        <div
          v-if="hasTurnOnButton"
          class="header_action_option"
          @click="multiTurn(1)"
        >
          <a-icon type="unlock" class="r_margin2" />
          <span>启用</span>
        </div>
        <div
          v-if="hasForbiddenButton"
          class="header_action_option"
          @click="multiTurn(0)"
        >
          <a-icon type="lock" class="r_margin2" />
          <span>禁用</span>
        </div>

        <div
          v-if="hasExportButton"
          class="header_action_option"
          @click="exportData"
        >
          <a-icon type="audit" class="r_margin2" />
          <span>导出数据</span>
        </div>

        <slot name="action_bar"></slot>
      </div>

      <div class="header_search_bar border_left border_right">
        <slot name="search_bar">
          <div class="flex_items_center">
            <table-search
              :searchForm="searchForm"
              :searchItems="searchItems"
              @doSearch="_getTable()"
            >
              <template v-slot="{ index }">
                <slot :searchForm="searchForm" :index="index" name="search" />
              </template>
            </table-search>
          </div>
        </slot>
      </div>
      <vxe-table
        :loading="loading"
        border
        highlight-hover-row
        ref="xTable"
        :export-config="{}"
        resizable
        :data="tableData"
        :size="tableSize ? tableSize : ''"
        @checkbox-change="selectChangeEvent"
        @checkbox-all="selectChangeEvent"
      >
        >
        <vxe-table-column
          v-for="(config, index) in tableColumn"
          :key="index"
          v-bind="config"
        >
          <template v-slot="{ row }" v-if="config.customRender">
            <slot :name="config.customRender" :record="row"></slot>
          </template>
        </vxe-table-column>
      </vxe-table>
    </div>
    <div class="table_footer border_top">
      <vxe-pager
        align="center"
        slot="footer"
        :loading="loading"
        :current-page="tablePage.page"
        :page-size="tablePage.page_size"
        :total="tablePage.total"
        :layouts="[
          'PrevJump',
          'PrevPage',
          'Number',
          'NextPage',
          'NextJump',
          'Sizes',
          'FullJump',
          'Total',
        ]"
        @page-change="handlePageChange"
      >
      </vxe-pager>
    </div>

    <template v-if="dialog.show">
      <a-modal
        :width="modalWidth || '50%'"
        :visible="dialog.show"
        :title="
          dialog.title || dialog.id
            ? `编辑 [${dialog.title}${titletext}]`
            : `新增 ${resource}`
        "
        @cancel="handleCancel"
        centered
      >
        <template slot="footer">
          <a-button key="back" @click="handleCancel"> 取消</a-button>
          <a-button key="submit" type="primary" @click="handleOk">
            提交
          </a-button>
        </template>
        <a-form-model ref="form" :model="dialog.model" :rules="rules">
          <div>
            <TableMod :data="dialog.model" :fieldNames="fieldNames">
              <template v-slot="{ index }">
                <slot :data="dialog.model" :index="index" name="form" />
              </template>
            </TableMod>
          </div>
        </a-form-model>
      </a-modal>
    </template>
  </div>
</template>

<script>
import TableSearch from "./tableSearch";
import TableMod from "./tableMod";
import util from "@/libs/util";

export default {
  components: { TableSearch, TableMod },
  props: {
    tableColumn: Array,
    title: { required: true, type: String },
    resource: { required: true, type: String },
    tableName: { required: true, type: String },
    titleKey: { type: String },
    titletext: { type: String, default: "" },
    Detail: {
      default: function () {
        return function () {
          return new Promise((resolve, reject) => {
            resolve();
          });
        };
      },
    },
    Table: {
      default: function () {
        return function () {
          return new Promise((resolve, reject) => {
            resolve();
          });
        };
      },
    },
    Update: {
      default: function () {
        return function () {
          return new Promise((resolve, reject) => {
            resolve();
          });
        };
      },
    },
    Create: {
      default: function () {
        return function () {
          return new Promise((resolve, reject) => {
            resolve();
          });
        };
      },
    },
    Delete: {
      default: function () {
        return function () {};
      },
    },
    rules: Object,
    isTab: Boolean,
    searchItems: Array,
    hasHeaderOperateBar: Boolean,
    hasAddButton: Boolean,
    hasDeleteButton: Boolean,
    hasExportButton: Boolean,
    hasTurnOnButton: Boolean,
    hasForbiddenButton: Boolean,
    fieldNames: Array,
    modalWidth: String,
    params: { type: Object, default: () => ({}) },
    tableSize: String,
  },
  data() {
    return {
      loading: false,
      tablePage: {
        page: 1,
        page_size: 10,
        total: 0,
      },
      selectedRowKeys: [],
      selectedRecords: [],
      dialog: {
        show: false,
        id: null,
        title: null,
        model: {},
      },
      searchForm: {},
      modalDefaultValue: {},
      tableData: [],
    };
  },

  methods: {
    //复选框选择改变
    selectChangeEvent({ records }) {
      this.selectedRecords = records;
      this.selectedRowKeys = records.map((item) => item.id);
    },
    // 表格获取数据
    _getTable(
      page = this.tablePage.page,
      page_size = this.tablePage.page_size
    ) {
      let params = {
        ...this.params,
        page,
        page_size,
        ...this.searchForm,
      };
      this.loading = true;
      this.Table(params)
        .then((res) => {
          this.tableData = res.list;
          this.tablePage.total = res.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    handlePageChange({ currentPage, page_size }) {
      this.tablePage.page = currentPage;
      this.tablePage.page_size = page_size;
      this._getTable();
    },
    // 打开表格弹窗，统一做新增和编辑操作
    openDia(item) {
      this.dialog.model = {};
      this.dialog.id = null;
      this.dialog.title = null;
      if (item) {
        this.Detail(item).then((res) => {
          this.dialog.title = item[this.titleKey];
          this.dialog.id = item.id;
          this.dialog.model = Object.assign(item);
          this.$forceUpdate();
          this.dialog.show = true;
        });
      } else {
        this.dialog.model = Object.assign(this.modalDefaultValue);
        this.$forceUpdate();
        this.dialog.show = true;
      }
    },
    // 批量操作前统一判断
    confirmMultiOperate(content = `确定要删除选中的数据吗？`) {
      return new Promise((resolve, reject) => {
        if (this.selectedRowKeys.length == 0) {
          this.$message.error("至少选择一条数据");
        } else {
          this.$confirm({
            title: "系统提示",
            content,
            okText: "确认",
            cancelText: "取消",
            onOk() {
              resolve();
            },
          });
        }
      });
    },
    // 删除表格数据
    multiDel(item = {}) {
      this.confirmMultiOperate().then((res) => {
        console.log(this.selectedRowKeys);
        // 调用批量删除接口
        this.$message.error("暂无批量操作接口");
      });
    },
    // 批量启用或者禁用
    multiTurn(validate) {
      this.confirmMultiOperate().then((res) => {
        console.log(this.selectedRowKeys);
        // 调用接口
        this.$message.error("暂无批量操作接口");
      });
    },

    // 弹窗-确认
    handleOk() {
      // 先进行表单校验
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 编辑表格数据
          let curd = null;
          let target = {};
          Object.assign(target, this.params, this.dialog.model);
          if (this.dialog.model.id) {
            console.log("执行编辑");
            curd = this.Update(target);
          } else {
            console.log("执行新增");
            curd = this.Create(target);
          }
          curd.then((res) => {
            this.handleCancel();
            this._getTable();
            if (res && res.code && !res.id) {
            } else {
              this.$message.success("操作成功");
            }
          });
        } else {
          this.$message.error("请填写完整数据");
        }
      });
    },
    // 弹窗-取消
    handleCancel() {
      this.dialog.show = false;
    },
    // 删除数据
    deleteData(data) {
      util.methods
        .confirm(this, `确定要删除该条${this.title}数据吗？`)
        .then((res) => {
          this.Delete(data).then((res) => {
            this._getTable();
            this.$message.success("操作成功");
          });
        });
    },
    // 部分表格数据操作-改变状态-禁用
    forbiddenData(data) {
      util.methods.confirm(this, `确定要改变数据状态吗？`).then((res) => {
        // 根据操作调用apis
        that.Update({ id: data.id, is_validate: 0 }).then((res) => {
          that._getTable();
        });
      });
    },
    // 获取添加数据时表单的默认值(导致添加时，保留上一次数据？？？)
    getModalDefaultValue() {
      if (this.fieldNames) {
        this.fieldNames.forEach((item) => {
          if (item.defaultValue) {
            this.modalDefaultValue[item.key] = item.defaultValue;
          }
        });
      }
    },
    // 导出数据
    exportData() {
      this.$refs.xTable.openExport({
        // 默认勾选源
        original: true,
      });
    },
  },
  created() {
    this._getTable();
  },
  mounted() {
    this.getModalDefaultValue();
  },
};
</script>
<style scoped>
.header_operate_bar {
  background: #ecf0f1;
  height: 40px;
  padding: 10px;
}

.header_search_bar {
  padding: 8px 10px;
}
.table_content {
  height: calc(100vh - 180px);
  overflow: hidden;
  overflow-y: auto;
}
.table_footer {
}
</style>
